package com.heima.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.Result;
import com.heima.domain.dto.PaetnerDto;
import com.heima.domain.dto.PartnerUpdateDto;
import com.heima.domain.po.Partner;
import com.heima.domain.vo.PaetnerByIdVo;
import com.heima.domain.vo.PartnerVo;
import com.heima.mapper.PartnerMapper;
import com.heima.service.PartnerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 合作商表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-06-06
 */
@Service
public class PartnerServiceImpl extends ServiceImpl<PartnerMapper, Partner> implements PartnerService {

    @Autowired
    private PartnerMapper partnerMapper;

    /**
     * 新增合作商
     *
     * @param dto
     * @return
     */
    @Override
    public Boolean addPartner(PaetnerDto dto) {
        Partner partner = new Partner();
        BeanUtils.copyProperties(dto,partner);
        partner.setPassword(BCrypt.hashpw(partner.getPassword(),BCrypt.gensalt()));
        partner.setCreateTime(LocalDateTime.now());
        partner.setUpdateTime(LocalDateTime.now());
        try {
            this.save(partner);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 分页查询合作商
     *
     * @param pageIndex
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public Result getByPage(Integer pageIndex, Integer pageSize, String name) {
        Page<Partner> page = new Page<>(pageIndex,pageSize);
        Page<PartnerVo> page2 = partnerMapper.getByPage(page,name);
        Result of = Result.of(page2);
        return of;
    }

    /**
     * 根据Id获取合作商
     *
     * @param id
     * @return
     */
    @Override
    public PaetnerByIdVo getPartnerById(Integer id) {
        PaetnerByIdVo vo = partnerMapper.getPartnerById(id);
        return vo;
    }

    /**
     * 修改合作商
     *
     * @param id
     * @return
     */
    @Override
    public Boolean updatePartner(Integer id, PartnerUpdateDto dto) {
        Partner partner = new Partner();
        BeanUtils.copyProperties(dto,partner);
        try {
            lambdaUpdate().eq(id != null, Partner::getId, id).update(partner);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除合作商
     *
     * @param id
     * @return
     */
    @Override
    public Boolean deletePartner(Integer id) {

        try {
            lambdaUpdate().eq(id != null, Partner::getId, id).remove();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
